package com.yans.managers
{
	import com.yans.consts.FishType;
	import com.yans.interfaces.IFish;
	import com.yans.interfaces.IRiverManager;
	
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.getTimer;
	
	public class RiverManager implements IRiverManager
	{
		public static var enterFrameTick:int;
		
		private var _swimTimes:uint;
		private var _startSec:Number;
		private var _fishes:Vector.<IFish>;
		private var _bigFishes:Vector.<IFish>;
		private var _water:int, _maxWater:int;
		//private var _fishes:Array;
		
		public function RiverManager(listener:IEventDispatcher, enterFrameTick:int=40, maxWater:int = 100){
			_maxWater = maxWater;
			_water = _maxWater;
			
			if(!listener) return;
			RiverManager.enterFrameTick = enterFrameTick;
//			_fishes = [];
			_fishes = new Vector.<IFish>();
			_bigFishes = new Vector.<IFish>();
			listener.addEventListener(Event.ENTER_FRAME, fishHandler);
			_startSec = getTimer();
			_swimTimes = 0;
		}
		
		public function removeFish(fish:IFish):void{
			var n:int = _fishes.indexOf(fish);
			if (n > -1){
				_fishes.splice(n, 1);
			}
			n = _bigFishes.indexOf(fish);
			if (n > -1) {
				_bigFishes.splice(n, 1);
			}
		}
		
		public function inRiver(fish:IFish):Boolean{
			var ret:Boolean = false;
			ret = _fishes.indexOf(fish) > -1;
			return ret;
			
		}
		
		private function onSwim(times:int, dt:Number):void{ 
			var tmp:IFish;
			var i:int = _bigFishes.length;
			
			while(i--) {
				if(_bigFishes.length > i) {
					_bigFishes[i].swim(times, dt);
				}
			}
			
			i = _fishes.length;
			while(i--)
			{
				if(_fishes.length > i) {
					_fishes[i].swim(times, dt);
				}
				if(_water < 0) {
					trace("#跳过", i);
					break;
				}
			} 
			_water = _maxWater;
		}
		
		/**
		 *	添加鱼 
		 * @param fish	鱼
		 * @param fishType	鱼类型
		 * @see com.yans.consts.FishType
		 */		
		public function addFish(fish:IFish, fishType:int = 1):void{
			if(fishType == FishType.BIG_FISH) {
				if(_bigFishes.indexOf(fish) == -1) {
					_bigFishes.push(fish);
				}
			}
			else if(fishType == FishType.SMALL_FISH) {
				if (_fishes.indexOf(fish) == -1){
					_fishes.push(fish);
				};
			}
		}
		
		private function fishHandler(evt:Event):void{ 
			var nt:uint = getTimer();			
			var dt:uint = nt - _swimTimes;
			var dtimes:int = dt / enterFrameTick; 
			if (dtimes > 3){
				onSwim(dtimes, dt);
			}
			else {
				onSwim(1, dt);
			};
			_swimTimes = nt;
		}
		
		public function clear():void
		{
			_fishes.length = 0;
		}
		
		public function reduce(water:int=1):void {
			_water -= water;
		}
		
	}
}